package com.zhiche.lisa.bms.service.price.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.mysql.jdbc.StringUtils;
import com.zhiche.lisa.bms.dao.mapper.price.PriceDeductRateMapper;
import com.zhiche.lisa.bms.dao.model.price.PriceDeductRate;
import com.zhiche.lisa.bms.pojo.vo.fee.FleetTypeVO;
import com.zhiche.lisa.bms.pojo.vo.price.PriceDedRateVO;
import com.zhiche.lisa.bms.service.price.PriceDeductRateService;
import com.zhiche.lisa.bms.service.utils.MdmUtil;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 支付扣点设置 服务实现类
 * </p>
 *
 * @author zhangkun
 * @since 2018-08-31
 */
@Service
public class PriceDeductRateServiceImpl extends ServiceImpl<PriceDeductRateMapper, PriceDeductRate> implements PriceDeductRateService {
    @Autowired
    private MdmUtil mdmUtil;
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(PriceDeductRateServiceImpl.class);

    /**
     * 支付扣点分页查询，返回结果按承运商名称排序
     *
     * @param page
     */
    @Override
    public Page<PriceDedRateVO> queryPriceDeductRate(Page<PriceDeductRate> page) {
        if (page == null) {
            throw new BaseException("分页参数不能为空");
        }
        Map<String, Object> cn = page.getCondition();
        Wrapper<PriceDeductRate> ew = buildCondition(cn);
        List<PriceDeductRate> priceDeductRateList = baseMapper.selectPage(page, ew);
        List<FleetTypeVO> fleetTypeList = mdmUtil.getAllFleetTypeByType();
        List<PriceDedRateVO> priceDedRateVos = Lists.newArrayList();
        for (PriceDeductRate priceDeductRate : priceDeductRateList) {
            PriceDedRateVO priceDedRateVo = new PriceDedRateVO();
            BeanUtils.copyProperties(priceDeductRate, priceDedRateVo);
            for (FleetTypeVO fleetType : fleetTypeList) {
                if (fleetType.getId().equals(priceDedRateVo.getFleetTypeId())) {
                    priceDedRateVo.setFleetType(fleetType.getValue());
                }
            }
            priceDedRateVos.add(priceDedRateVo);

        }
        Page<PriceDedRateVO> priceDedRateVOPage = new Page<>();
        BeanUtils.copyProperties(page, priceDedRateVOPage);
        priceDedRateVOPage.setRecords(priceDedRateVos);
        return priceDedRateVOPage;
    }

    private Wrapper<PriceDeductRate> buildCondition(Map<String, Object> condition) {
        Wrapper<PriceDeductRate> ew = new EntityWrapper<>();
        ew.orderBy("gmt_create desc, id desc");
        if (!Objects.isNull(condition) && !condition.isEmpty()) {
            //根据承运商名称查询
            Object lspName = condition.get("lspName");
            if (lspName != null && !StringUtils.isNullOrEmpty(lspName.toString())) {
                ew.eq("lsp_name", lspName.toString());
            }
            //根据车队名称查询
            Object fleetName = condition.get("fleetName");
            if (fleetName != null && !StringUtils.isNullOrEmpty(fleetName.toString())) {
                ew.eq("fleet_name", fleetName.toString());
            }
            //根据车队类型查询
            Object fleetTypeId = condition.get("fleetTypeId");
            if (fleetTypeId != null && !StringUtils.isNullOrEmpty(fleetTypeId.toString())) {
                ew.eq("fleet_type_id", fleetTypeId.toString());
            }
            //根据有效期查询
            Object effectiveDate = condition.get("effectiveDate");
            Object invalidDate = condition.get("invalidDate");
            if (effectiveDate != null && !StringUtils.isNullOrEmpty(effectiveDate.toString())) {
                ew.ge("effective_date", effectiveDate);

            }
            if (invalidDate != null && !StringUtils.isNullOrEmpty(invalidDate.toString())) {
                ew.le("effective_date", invalidDate);
            }
        }
        ew.orderBy("lspId", true);
        ew.orderBy("gmt_create", true);
        return ew;
    }

    /**
     * 新增承运商一条数据
     *
     * @param priceDeductRate
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PriceDeductRate insertPriceDeductRate(PriceDeductRate priceDeductRate) {
        PriceDeductRate cn = null;
        JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
        if (Objects.isNull(jwtAccountVO)) throw new BaseException("未获取登录信息");
        //判断该承运商是否存在

        if ("10".equals(priceDeductRate.getSubjectType())) {
            if (!priceDeductRate.getLspName().isEmpty() && priceDeductRate.getLspId() != null) {
                updateInvalideDate(priceDeductRate);
                cn = insertLspRate(priceDeductRate);
            } else {
                throw new BaseException("承运商名称和ID不能为空!");
            }
        } else if ("20".equals(priceDeductRate.getSubjectType())) {
            if (!priceDeductRate.getFleetName().isEmpty() && priceDeductRate.getFleetId() != null) {
                updateInvalideDate(priceDeductRate);
                cn = insertFleetRate(priceDeductRate);
            }
        }
        return cn;

    }

    /**
     * 更新车队和承运商扣点的失效日期和支付方式失效日期
     *
     * @param priceDeductRate
     */
    private void updateInvalideDate(PriceDeductRate priceDeductRate) {
        EntityWrapper<PriceDeductRate> ew = new EntityWrapper<>();
        if ("10".equals(priceDeductRate.getSubjectType())) {
            ew.eq("lsp_id", priceDeductRate.getLspId()).eq("subject_type", priceDeductRate.getSubjectType());
            ew.isNull("invalid_date");
        }
        if ("20".equals(priceDeductRate.getSubjectType())) {
            ew.eq("fleet_id", priceDeductRate.getFleetId());
            ew.andNew().isNull("pay_invalid_date").or().isNull("invalid_date");
        }
        List<PriceDeductRate> list = this.selectList(ew);
        if (!CollectionUtils.isEmpty(list)) {
            for (PriceDeductRate priceDeductRate1 : list) {
                if (priceDeductRate1.getInvalidDate() == null) {
                    if (priceDeductRate1.getEffectiveDate().compareTo(priceDeductRate.getEffectiveDate()) > 0) {
                        throw new BaseException("车队扣点生效时间已存在已有数据中");
                    }
                    priceDeductRate1.setInvalidDate(priceDeductRate.getEffectiveDate());
                    priceDeductRate1.updateById();
                }
//                if (priceDeductRate1.getPayInvalidDate() == null && priceDeductRate1.getFleetId() != null
//                        && priceDeductRate1.getPayWay() != null && priceDeductRate1.getPayWay() == 0) {
//                    if (priceDeductRate1.getPayEffectiveDate().compareTo(priceDeductRate.getPayEffectiveDate()) > 0) {
//                        throw new BaseException("支付生效时间已存在已有数据中");
//                    }
//                    priceDeductRate1.setPayInvalidDate(priceDeductRate.getPayEffectiveDate());
//                    priceDeductRate1.updateById();
            }
        }
    }


    /**
     * 新增承运商特有信息
     *
     * @param priceDeductRate
     * @return
     */
    private PriceDeductRate insertLspRate(PriceDeductRate priceDeductRate) {
        priceDeductRate.setLspId(priceDeductRate.getLspId());
        priceDeductRate.setLspName(priceDeductRate.getLspName());
        priceDeductRate.setRate(priceDeductRate.getRate());
        priceDeductRate.setEffectiveDate(priceDeductRate.getEffectiveDate());
        priceDeductRate = insertConmon(priceDeductRate);
        return priceDeductRate;
    }

    /**
     * 新增车队特有扣点信息
     *
     * @param priceDeductRate
     * @return
     */
    private PriceDeductRate insertFleetRate(PriceDeductRate priceDeductRate) {
//        BigDecimal a, b, c, d;
//        priceDeductRate.setFleetId(priceDeductRate.getFleetId());
//        priceDeductRate.setFleetName(priceDeductRate.getFleetName());
//        priceDeductRate.setFleetTypeId(priceDeductRate.getFleetTypeId());
//        priceDeductRate.setRate(priceDeductRate.getRate());
//        priceDeductRate.setEffectiveDate(priceDeductRate.getEffectiveDate());


//        priceDeductRate.setPayWay(priceDeductRate.getPayWay());
//        if (priceDeductRate.getPayWay() == 0) {
//            priceDeductRate.setPayEffectiveDate(priceDeductRate.getPayEffectiveDate());
//        }
//        // 校验油卡比例与现金比例之和是否等于1
//        if (priceDeductRate.getOilFinalpayRate() != null) {
//            a = priceDeductRate.getOilFinalpayRate();
//        } else {
//            a = BigDecimal.valueOf(0);
//        }
//        if (priceDeductRate.getOilPrepayRate() != null) {
//            b = priceDeductRate.getOilPrepayRate();
//        } else {
//            b = BigDecimal.valueOf(0);
//        }
//        if (priceDeductRate.getCashFinalpayRate() != null) {
//            c = priceDeductRate.getCashFinalpayRate();
//        } else {
//            c = BigDecimal.valueOf(0);
//        }
//        if (priceDeductRate.getCashPrepayRate() != null) {
//            d = priceDeductRate.getCashPrepayRate();
//        } else {
//            d = BigDecimal.valueOf(0);
//        }
//        BigDecimal sum = a.add(b).add(c).add(d);
//        if (!(sum.compareTo(BigDecimal.valueOf(1)) == 1)) {
//            priceDeductRate.setOilFinalpayRate(priceDeductRate.getOilFinalpayRate());
//            priceDeductRate.setOilPrepayRate(priceDeductRate.getOilPrepayRate());
//            priceDeductRate.setCashFinalpayRate(priceDeductRate.getCashFinalpayRate());
//            priceDeductRate.setCashPrepayRate(priceDeductRate.getCashPrepayRate());
//        } else {
//            throw new BaseException("油卡比例与现金比例之和大于1");
//        }
//        priceDeductRate.setFleetTypeName(priceDeductRate.getFleetTypeName());
        priceDeductRate = insertConmon(priceDeductRate);

        return priceDeductRate;
    }

    /**
     * 新增车队与承运商共有信息
     *
     * @param priceDeductRate
     * @return
     */
    private PriceDeductRate insertConmon(PriceDeductRate priceDeductRate) {
        JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
        priceDeductRate.setTenantId(new Long(jwtAccountVO.getTenantId()));
        priceDeductRate.setCreator(Long.valueOf(jwtAccountVO.getAccountId()));
        priceDeductRate.setGmtCreate(new Date());
        this.insert(priceDeductRate);
        return priceDeductRate;
    }


    /**
     * 传入车队ID和承运商ID返回扣点系数
     *
     * @param lspId
     * @param fleetId
     * @return
     */
    @Override
    public PriceDeductRate returnPriceDeductRate(Long lspId, Long fleetId) {
        List<PriceDeductRate> list = null;
        //根据车队ID查询
        Wrapper<PriceDeductRate> ew = new EntityWrapper<>();
        ew.eq("fleet_id", fleetId).eq("subject_type", "20");
        ew.le("effective_date", new Date());
        ew.andNew().ge("invalid_date", new Date()).or().isNull("invalid_date");
        list = baseMapper.selectListNoTenant(ew);
        if (CollectionUtils.isEmpty(list)) {
            //再根据承运商ID查询
            Wrapper<PriceDeductRate> ewLsp = new EntityWrapper<>();
            ewLsp.eq("lsp_id", lspId).eq("subject_type", "10");
            ewLsp.le("effective_date", new Date());
            ewLsp.andNew().ge("invalid_date", new Date()).or().isNull("invalid_date");
            list = baseMapper.selectListNoTenant(ewLsp);
        }
        if (CollectionUtils.isEmpty(list)) {
            return null;
        } else {
            return list.get(0);
        }
    }

    /**
     * 根据车队id获取对应的扣点比例
     *
     * @param fleetId
     * @return
     */
    @Override
    public PriceDeductRate returnPriceDeductRateByFleetId(Long fleetId) {
        List<PriceDeductRate> cn = null;
        //再根据车队ID查询
        Wrapper<PriceDeductRate> ew = new EntityWrapper<>();
        ew.eq("fleet_id", fleetId).eq("subject_type", "20");
//        ew.le("pay_effective_date", new Date());
//        ew.andNew().ge("pay_invalid_date", new Date()).or().isNull("pay_invalid_date");
        cn = baseMapper.selectListNoTenant(ew);
        if (CollectionUtils.isEmpty(cn)) {
            return null;
        } else {
            return cn.get(0);
        }
    }


}
